package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.model.domain.SystemInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/sys-info")
public class SystemInfoController {

    /**
     * 获取系统参数信息
     *
     * @return
     */
    @GetMapping()
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<SystemInfo> getSystemInfo() {
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        FileStore store = null;
        try {
            store = Files.getFileStore(Paths.get("."));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取CPU负载
        double cpuLoad = osBean.getSystemLoadAverage();

        // 获取内存使用情况
        MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();
        MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();

        // 获取JVM启动时间
        long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();

        // 获取JVM运行时间
        long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();

        // 获取磁盘空间使用情况
        long totalSpace = 0;
        long usedSpace = 0;
        long freeSpace = 0;
        try {
            totalSpace = store.getTotalSpace();
            usedSpace = totalSpace - store.getUnallocatedSpace();
            freeSpace = store.getUsableSpace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        SystemInfo systemInfo = new SystemInfo(cpuLoad, heapMemoryUsage, nonHeapMemoryUsage, jvmStartTime, jvmUptime, totalSpace, usedSpace, freeSpace);

        return ResultUtils.success(systemInfo);
    }
    
}
